import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Tabs, InfiniteScroll, Badge } from "antd-mobile";
import styles from "./index.module.css";
import http from "../../utils/http";
import Mylist from "../../components/Mylist";

const Index = () => {
  const navigate = useNavigate();
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");

  const [HomeList, setHomeList] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [collectList,setCollectList]=useState(
        JSON.parse(localStorage.getItem('collectList')) || []
    )
    const handelColl=(item)=>{
        const collState =collectList.some((it)=>it.id===item.id)
        if(collState){
            const filterList=collectList.filter((it)=>it.id !== item.id)
            setCollectList(filterList)
            localStorage.setItem('collectList',JSON.stringify(filterList))
        }else{
            setCollectList([...collectList,item])
            localStorage.setItem(
                'collectList',
                JSON.stringify([...collectList,item])
            )
        }
    }
  //请求数据
  const getList = async () => {
    const res = await http.get("/api/list", { params: { page } });
    const { data } = res.data;
    setHomeList([...HomeList, ...data]);
    setPage((prev) => prev + 1);

    if (data.length === 0) {
      setHasMore(false);
    }
  };

  useEffect(() => {
    getList();
  }, []);

  return (
    <div>
      <div className={styles.Header}>
        <div className={styles.head_title}>
          <h3>订票服务</h3>
          <div className={styles.head_t_right}>
            <Badge content={Badge.dot}>
              <span onClick={() => navigate("/message")}>通知</span>
            </Badge>

            <img className={styles.avatarimg} src={userInfo.avatar}></img>
          </div>
        </div>
      </div>
      <Tabs>
        <Tabs.Tab title="最新活动块" key="tab1">
          {HomeList.length > 0 &&
            HomeList.map((item, ind) => <Mylist itemData={item} key={ind} />)}
          <InfiniteScroll loadMore={getList} hasMore={hasMore} />
        </Tabs.Tab>
        <Tabs.Tab title="类别块" key="tab2">
          类别块
        </Tabs.Tab>
        <Tabs.Tab title="进行中快" key="tab3">
          进行中快
        </Tabs.Tab>
      </Tabs>
    </div>
  );
};

export default Index;
